import immutable from '../../../lib/immutable';
import getIn from '../../../utils/getIn';
import loadFieldList from './loadFieldList';
import { CONTENT_TYPE_CATE, CONTENT_TYPE_DEFAULT } from '../element/List';

/**
 * 获取列表组件的参数集
 * @param metaData
 * @param extra
 * @returns {object}
 */
export default function listElementParams(metaData, extra = {}) {
    if (extra && extra.toJS) extra = extra.toJS();
    const set_id = getIn(extra, ['set_id']) || metaData.getIn(['fieldSet', 'id']);// 模型id,如果url上面有模型id，优先使用
    let content_type = metaData.getIn(['element', 'content_type']) || CONTENT_TYPE_DEFAULT;
    const field_needs = metaData.getIn(['fieldSet', 'needs']) ? metaData.getIn(['fieldSet', 'needs']).toJS() : []; // 必要字段
    const fields = loadFieldList(metaData).concat(field_needs).join(',');
    const keywords = getIn(extra, ['keywords']);
    const sort = metaData.getIn(['element', 'sort']);
    const order = metaData.getIn(['element', 'order']);
    const rows = metaData.getIn(['element', 'rows']) || 10;
    const cate_id = getIn(extra, ['cate_id']);
    let list;
    const content = metaData.getIn(['element', 'content_list'])
        && metaData.getIn(['element', 'content_list'])
            .filter(d => d.get('set_id') === set_id && d.get('content_type') === content_type);
    if (content && content.size > 0) {
        const data = content.getIn([0, 'data']);
        list = data && data.map(d => d.get('id')).join(',');
    }
    if (cate_id) {
        content_type = CONTENT_TYPE_CATE;
        list = cate_id;
    }
    return immutable.fromJS({
        set_id,
        keywords,
        fields,
        list,
        content_type,
        sort,
        order,
        rows,
    });
}
